<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="药品编号" prop="medicineId">
        <el-input v-model="queryParams.medicineId" placeholder="请输入药品编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="患者名称" prop="patientName">
        <el-input v-model="queryParams.patientName" placeholder="请输入患者名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">

        <el-select v-model="queryParams.gender" placeholder="性别" clearable>
          <el-option label="男" value='0'></el-option>
          <el-option label="女" value='1'></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="电话" prop="contactPhone">
        <el-input v-model="queryParams.contactPhone" placeholder="请输入电话" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="住址" prop="homeAddress">
        <el-input v-model="queryParams.homeAddress" placeholder="请输入住址" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="数量" prop="quantityPrescribed">
        <el-input v-model="queryParams.quantityPrescribed" placeholder="请输入数量" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable v-model="queryParams.createTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <!--      <el-form-item label="总价" prop="totalPrice">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.totalPrice"-->
      <!--          placeholder="请输入总价"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="状态" prop="isArchived">
        <el-select v-model="queryParams.isArchived" placeholder="状态" clearable>
          <el-option label="未归档" value='0'></el-option>
          <el-option label="归档" value='1'></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="修改时间" prop="updateTime">
        <el-date-picker clearable v-model="queryParams.updateTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请输入修改时间">
        </el-date-picker>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:sale:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single || hasArchived"
          @click="handleUpdate" v-hasPermi="['system:sale:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:sale:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:sale:export']">导出</el-button>
      </el-col>


      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="saleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="药品名称" align="center" prop="medicineName">
        <template slot-scope="scope">
          <span>{{ scope.row.sysMedicines.medicineName }}</span>
        </template>

      </el-table-column>
      <el-table-column label="患者名称" align="center" prop="patientName" />
      <el-table-column label="性别" align="center" prop="gender">
        <template slot-scope="scope">
          {{ scope.row.gender === '1' ? '女' : '男' }}
        </template>
      </el-table-column>
      <el-table-column label="电话" align="center" prop="contactPhone" />
      <el-table-column label="住址" align="center" prop="homeAddress" />
      <el-table-column label="开药医生名称" align="center" prop="doctorName" />
      <el-table-column label="数量" align="center" prop="quantityPrescribed" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总价" align="center" prop="totalPrice">
        <template slot-scope="scope">
          <span>{{ (scope.row.quantityPrescribed) * (scope.row.sysMedicines.price) }}</span>
        </template>

      </el-table-column>


      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isArchived === '1' ? 'success' : 'danger'">
            {{ scope.row.isArchived === '1' ? '归档' : '未归档' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:sale:edit']" :disabled="scope.row.isArchived === '1'">修改</el-button>
          
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:sale:remove']">删除</el-button>


          <el-button size="mini" type="text" icon="el-icon-edit" @click="handlearchived(scope.row)"
            v-hasPermi="['system:sale:archived']" :disabled="scope.row.isArchived === '1' ">归档</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改销售信息管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="药品编号" prop="medicineId">
          <el-input v-model="form.medicineId" placeholder="请输入药品编号" />
        </el-form-item> -->

        <el-form-item label="药品" prop="medicineId">
          <el-select v-model="form.medicineId" placeholder="请选择药品" @change="handleMedicineChange" filterable clearable
            style="width: 100%">
            <!-- <el-option v-for="item in medicineOptions" :key="item.medicineId"
              :label="`${item.medicineName} (库存: ${item.stockQuantity})`" :value="item.medicineId"> -->
            <el-option v-for="item in medicineOptions" :key="item.medicineId" :label="`${item.medicineName}`"
              :value="item.medicineId">
              <span style="float: left">{{ item.medicineName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                <!-- 库存: {{ item.stockQuantity }}  -->单价: {{ item.price }}元
              </span>
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="患者名称" prop="patientName">
          <el-input v-model="form.patientName" placeholder="请输入患者名称" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="性别" clearable>
            <el-option label="男" value='0'></el-option>
            <el-option label="女" value='1'></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="住址" prop="homeAddress">
          <el-input v-model="form.homeAddress" placeholder="请输入住址" />
        </el-form-item>
        <!-- <el-form-item label="数量" prop="quantityPrescribed">
          <el-input v-model="form.quantityPrescribed" placeholder="请输入数量" />
        </el-form-item> -->
        <!-- <el-form-item label="总价" prop="totalPrice">
          <el-input v-model="totalPrice()" placeholder="请输入总价" read />
        </el-form-item> -->
        <el-form-item label="数量" prop="quantityPrescribed">
          <el-input v-model.number="form.quantityPrescribed" placeholder="请输入数量" @input="calculateTotalPrice" />
        </el-form-item>

        <el-form-item label="总价" prop="totalPrice">
          <el-input v-model="form.totalPrice" placeholder="自动计算" :readonly="true" />
        </el-form-item>

        <!-- <el-form-item label="总价">
          <el-input :value="totalPrice" placeholder="自动计算" readonly />
        </el-form-item> -->

        <!-- <el-form-item label="状态" prop="isArchived">
          <el-select v-model="form.isArchived" placeholder="状态" clearable>
            <el-option label="未归档" value='0'></el-option>
            <el-option label="归档" value='1'></el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSale, getSale, delSale, addSale, updateSale, archivedSale } from "@/api/system/sale";
import { listMedicine } from "@/api/system/medicine";

export default {
  name: "Sale",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      //
      hasArchived: false, // 选中行是否包含归档记录
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售信息管理表格数据
      saleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        medicineId: null,
        patientName: null,
        gender: null,
        contactPhone: null,
        homeAddress: null,
        doctorId: null,
        quantityPrescribed: null,
        createTime: null,
        totalPrice: null,
        isArchived: '0',
        updateTime: null,
        updateBy: null,
        createBy: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        medicineId: [
          { required: true, message: "药品名称不能为空", trigger: "blur" }
        ],
        patientName: [
          { required: true, message: "患者名称不能为空", trigger: "blur" }
        ],
        gender: [
          { required: true, message: "性别不能为空", trigger: "blur" }
        ],

        contactPhone: [
          {
            required: true,
            message: "请输入联系电话",
            trigger: "blur"
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入有效的手机号码",
            trigger: "blur"
          }
        ],

        homeAddress: [
          { required: true, message: "患者住址不能为空", trigger: "blur" }
        ],

        quantityPrescribed: [
          { required: true, message: "销售药瓶数量不能为空且必须为数字", pattern: /^-?\d+(\.\d+)?$/, trigger: "blur" }

        ],






      },
      medicineOptions: [],
      currentMedicinePrice: 0, // 当前选中药品的单价

     
    };
  },
  created() {
    this.getList();
    this.getMedicineList();
  },

  computed: {
    // 新增计算属性
    totalPrice() {
      const price = parseFloat(this.form.price) || 0;
      const quantity = parseFloat(this.form.stockQuantity) || 0;
      return (price * quantity).toFixed(2);
    },
    // 其他计算属性...
  },
  methods: {
    getMedicineList() {
      listMedicine({
        pageNum: 1,
        pageSize: 1000, // 根据实际数据量调整
        status: 1 // 只显示已审核药品
      }).then(response => {
        this.medicineOptions = response.rows;
      });
    },


    // 当药品选择变化时获取价格
    handleMedicineChange(medicineId) {
      const selected = this.medicineOptions.find(item => item.medicineId === medicineId);
      if (selected) {
        this.currentMedicinePrice = selected.price;
        this.calculateTotalPrice();
      }
    },

    // 计算总价
    calculateTotalPrice() {
      if (
        this.currentMedicinePrice > 0 &&
        this.form.quantityPrescribed > 0
      ) {
        this.form.totalPrice = (
          this.currentMedicinePrice * this.form.quantityPrescribed
        ).toFixed(2);
      } else {
        this.form.totalPrice = 0;
      }
    },
    /** 查询销售信息管理列表 */
    getList() {
      this.loading = true;
      listSale(this.queryParams).then(response => {
        this.saleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        prescriptionId: null,
        medicineId: null,
        patientName: null,
        gender: null,
        contactPhone: null,
        homeAddress: null,
        doctorId: null,
        quantityPrescribed: null,
        createTime: null,
        totalPrice: null,
        isArchived: '0',
        updateTime: null,
        updateBy: null,
        createBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.prescriptionId)
      this.single = selection.length !== 1
      this.multiple = !selection.length

      // 新增：检查选中行是否包含归档记录
      this.hasArchived = selection.some(item => item.isArchived === '1')
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加销售信息管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const prescriptionId = row.prescriptionId || this.ids
      getSale(prescriptionId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改销售信息管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.prescriptionId != null) {
            updateSale(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSale(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const prescriptionIds = row.prescriptionId || this.ids;
      this.$modal.confirm('是否确认删除销售信息管理编号为"' + prescriptionIds + '"的数据项？').then(function () {
        return delSale(prescriptionIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },


    //归档
    handlearchived(row) {
      const prescriptionIds = row.prescriptionId || this.ids;
      console.log("id",row)
      archivedSale(prescriptionIds).then(response => {
        this.getList();
        this.$modal.msgSuccess("归档成功");
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/sale/export', {
        ...this.queryParams
      }, `sale_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
